package cn.test.forkjoin.fj;

import java.util.concurrent.RecursiveTask;

public class LongSumTask extends RecursiveTask<Long> {
    // 任务拆分最小阈值
    static final int SEQUENCIAL_THRESHOLD = 10000000;

    int low;
    int high;
    int[] array;

    public LongSumTask(int low, int high, int[] array) {
        this.low = low;
        this.high = high;
        this.array = array;
    }

    @Override
    protected Long compute() {
        // 当任务拆分到小于等于阈值时开始求和
        if (high - low < SEQUENCIAL_THRESHOLD) {
            long sum = 0;
            for (int i = low; i < high; i++) {
                sum += array[i];
            }
            return sum;
        } else {//任务过大继续拆分
            int mid = low + (high - low) / 2;
            LongSumTask left = new LongSumTask(low, mid, array);
            LongSumTask right = new LongSumTask(mid, high, array);

            // 提交任务
            left.fork();
            right.fork();

            // 获取任务的执行结果，将阻塞当前线程直到对应的子任务完成运行并返回结果
            Long rightSum = right.join();
            Long leftSum = left.join();

            return leftSum + rightSum;
        }
    }
}
